package com.example.yskjproject.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.yskjproject.R;
import com.example.yskjproject.adapter.ContentAdapter;
import com.example.yskjproject.adapter.ScreenAdapter;
import com.example.yskjproject.base.BaseFragment;
import com.example.yskjproject.content.Content;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.databinding.UniversalDisplayFragmentBinding;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.CardListModel;
import com.example.yskjproject.model.CardModel;
import com.example.yskjproject.model.LeftMenuModel;
import com.example.yskjproject.model.LeftModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.OrderListModel;
import com.example.yskjproject.utils.Log;
import com.example.yskjproject.utils.LogUtils;
import com.example.yskjproject.utils.SpCashUtils;
import com.example.yskjproject.view.FullyStaggeredGridLayoutManager;
import com.example.yskjproject.view.dialog.LoginWorkDialogHelper;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * UniversalDisplayFragment  通用显示的fragment
 * <p>
 * 作者：zx
 * 创建时间：2024/4/16
 */
public class UniversalDisplayFragment extends BaseFragment<UniversalDisplayFragmentBinding> {
    private UniversalDisplayFragmentBinding universalBinding;
    private ScreenAdapter screenAdapter;
    private List<LeftMenuModel> level3Date = Lists.newArrayList();
    private ContentAdapter contentAdapter;
    private List<String> level3ListDate = Lists.newArrayList();
    private int level1Id, level2Id;
    private List<CardModel> listCardDate = Lists.newArrayList();

    private LoginWorkDialogHelper loginWorkDialogHelper;
    public static int mCurrentPage = 1;
    public static final int mPageSize = 10;
    private FullyStaggeredGridLayoutManager layoutManager;
    private int oldSize;
    private boolean isLoading = false;
    private int pageTotal = 2;


    public static UniversalDisplayFragment newInstance(int level1Id, int level2Id) {
        Bundle args = new Bundle();
        args.putInt("level1Id", level1Id);
        args.putInt("level2Id", level2Id);
        UniversalDisplayFragment fragment = new UniversalDisplayFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected UniversalDisplayFragmentBinding onCreateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent) {
        universalBinding = UniversalDisplayFragmentBinding.inflate(inflater, parent, false);
        return universalBinding;
    }

    @Override
    protected void onData() {
        getLevel3();
//        String text = getArguments() != null ? getArguments().getString("text") : null;
        level1Id = getArguments() != null ? getArguments().getInt("level1Id") : -1;
        level2Id = getArguments() != null ? getArguments().getInt("level2Id") : -1;
        universalBinding.screenRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        screenAdapter = new ScreenAdapter(R.layout.item_screen, level3Date, getActivity());
        universalBinding.screenRv.setAdapter(screenAdapter);
        screenAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mCurrentPage = 1;
            if (position == 0) {
                level3Date.get(0).setSelect(true);
                for (int i = 1; i < level3Date.size(); i++) {
                    level3Date.get(i).setSelect(false);
                }
                level3ListDate.clear();
                getCardInfoDate(level3ListDate);
            } else {
                level3Date.get(0).setSelect(false);
                if (!level3ListDate.contains(String.valueOf(level3Date.get(position).getId()))) {
                    level3Date.get(position).setSelect(true);
                    level3ListDate.add(String.valueOf(level3Date.get(position).getId()));
                } else {
                    level3Date.get(position).setSelect(false);
                    level3ListDate.remove(String.valueOf(level3Date.get(position).getId()));
                }
            }
            screenAdapter.notifyDataSetChanged();
            isLoading = true;
            getCardInfoDate(level3ListDate);
        });

        //瀑布流
        // 获取屏幕尺寸
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        display.getMetrics(displayMetrics);

        // 屏幕尺寸（像素）
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;

        // 打印尺寸
        LogUtils.d("ScreenSize" + "Width: " + width + ", Height: " + height);
        if (width > 3000) {
            layoutManager = new FullyStaggeredGridLayoutManager(4, FullyStaggeredGridLayoutManager.VERTICAL);
            layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
            universalBinding.contentRv.setLayoutManager(layoutManager);
        } else {
            layoutManager = new FullyStaggeredGridLayoutManager(3, FullyStaggeredGridLayoutManager.VERTICAL);
            layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
            universalBinding.contentRv.setLayoutManager(layoutManager);

        }
        contentAdapter = new ContentAdapter(getActivity(), listCardDate, getActivity(), universalBinding.contentRv.getWidth());
        universalBinding.contentRv.setAdapter(contentAdapter);
        universalBinding.contentRv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                universalBinding.contentRv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                contentAdapter.setRecyclerViewWidth(universalBinding.contentRv.getWidth());
            }
        });
        ((DefaultItemAnimator) universalBinding.contentRv.getItemAnimator()).setSupportsChangeAnimations(false);
        ((SimpleItemAnimator) universalBinding.contentRv.getItemAnimator()).setSupportsChangeAnimations(false);
        universalBinding.contentRv.getItemAnimator().setChangeDuration(0);
        universalBinding.contentRv.setHasFixedSize(true);
        universalBinding.contentRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//                StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
//                if (layoutManager != null) {
//                    int totalItemCount = layoutManager.getItemCount();
//                    int[] lastVisibleItemPositions = layoutManager.findLastVisibleItemPositions(new int[layoutManager.getSpanCount()]);
//                    // 检查所有列的最大值
//                    int maxPos = getMaxPosition(lastVisibleItemPositions);
//
//                    boolean isAtBottom = maxPos >= totalItemCount - 1;
//
//                    if (isAtBottom && !recyclerView.canScrollVertically(1)) {
//                        // 已经滚动到底部，加载下一页数据
//                        getCardInfoDate(level3ListDate);
//                    }
//                }
                if (dy > 0) { // 向下滑动时
                    layoutManager.invalidateSpanAssignments();
                }
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
//                if (layoutManager != null) {
//                    layoutManager.invalidateSpanAssignments();
//                    int totalItemCount = layoutManager.getItemCount();
//                    int[] lastVisibleItemPositions = layoutManager.findLastVisibleItemPositions(new int[layoutManager.getSpanCount()]);
//                    int maxPos = getMaxPosition(lastVisibleItemPositions);
//
//                    if (newState == RecyclerView.SCROLL_STATE_IDLE) { // 用户停止滚动
//                        if (maxPos >= totalItemCount - 1 && !recyclerView.canScrollVertically(1)) {
//                            // 已经滚动到底部，加载下一页数据
//                            getCardInfoDate(level3ListDate);
//                        }
//                    }
//                }
//                if (!recyclerView.canScrollVertically(1) && newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    LogUtils.d("UniversalDisplayFragment"+"滑动到底部了，加载下一页数据" + oldSize);
//                    if (oldSize >= 10) {
//                        mCurrentPage++;
//                        getCardInfoDate(level3ListDate);
//                    } else {
//                        ToastUtil.toastShortMessage("没有更多数据了");
//                    }
//
//                }
//                if (!recyclerView.canScrollVertically(-1) && newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    mCurrentPage = 1;
//                    LogUtils.d("UniversalDisplayFragment"+"滑动到顶部了，加载上一页数据");
//                    getCardInfoDate(level3ListDate);
//                }
//            }
                if (!isLoading && !recyclerView.canScrollVertically(1) && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 滑动到底部，加载下一页
                    if (oldSize >= mPageSize) {
                        isLoading = true;
                        mCurrentPage++;
                        getCardInfoDate(level3ListDate);
                    } else {
                        ToastUtil.toastShortMessage("没有更多数据了");
                    }
                }

                if (!isLoading && !recyclerView.canScrollVertically(-1) && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 滑动到顶部，重新加载第一页
                    isLoading = true;
                    mCurrentPage = 1;
                    getCardInfoDate(level3ListDate);
                }
            }
        });

        universalBinding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                isLoading = true;
                getCardInfoDate(level3ListDate);
            }
        });
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    //登录之后  通知瀑布流
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEvent(EventMessage eventMsg) {
        switch (eventMsg.getMessage()) {
            case EventContent.updateState:
                mCurrentPage = 1;
                getCardInfoDate(level3ListDate);
                break;
        }

    }


    /**
     * 获取瀑布流内容
     */
    private void getCardInfoDate(List<String> level3Id) {
        if (mCurrentPage > pageTotal) {
            isLoading = false; // 重置标志位
            universalBinding.swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
            ToastUtil.toastShortMessage("没有更多数据了");
            return;
        }
        new Thread(() -> {
            String ulr = "";
            String ids3 = "";
            StringBuilder sb = new StringBuilder();
            if (!level3Id.isEmpty()) {
                for (int a = 0; a < level3Id.size(); a++) {
                    String s = level3Id.get(a);
                    sb.append("&tag_lv3_id=" + s);
                }
                ids3 = sb.toString();
            }
            LogUtils.d("UniversalDisplayFragment"+"当前页码" + mCurrentPage);
            if (mCurrentPage >= pageTotal) {
                ToastUtil.toastShortMessage("没有更多数据了");
                return;
            }

            if (TextUtils.isEmpty(SpCashUtils.getInstance().getToken())) {//没有登录
                ulr = Urls.CONTENT_CARD_INFO_NO + "?tag_lv1_id=" + level1Id + "&tag_lv2_id=" + level2Id + "&tag_lv3_id=" + ids3 + "&page=" + mCurrentPage + "&limit=" + mPageSize;
            } else {
                ulr = Urls.CONTENT_CARD_INFO + "?tag_lv1_id=" + level1Id + "&tag_lv2_id=" + level2Id + ids3 + "&page=" + mCurrentPage + "&limit=" + mPageSize;
            }
            Log.e("ulr====-=" + ulr);
            Type type = new TypeToken<LzyResponse<CardListModel>>() {
            }.getType();
            APIService.<LzyResponse<CardListModel>>getData(type, ulr).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<CardListModel>() {
                @Override
                public void onSubscribe(Disposable d) {
                    Log.e("onSubscribe ： " + d);
                }

                @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet"})
                @Override
                public void onNext(CardListModel cardListModel) {
                    for (int i = 0; i < cardListModel.getStudio_list().size(); i++) {
                        LogUtils.d("UniversalDisplayFragment"+"UniversalDisplayFragment" + cardListModel.getStudio_list().get(i).getTitle() + "图片" + cardListModel.getStudio_list().get(i).getMedia_list().get(0).getMedia_url());
                    }
                    pageTotal = cardListModel.getTotal();
                    oldSize = cardListModel.getStudio_list().size();

                    if (mCurrentPage == 1) {
                        listCardDate.clear(); // 如果是第一页，清空数据
                        contentAdapter.notifyDataSetChanged();
                    }

                    listCardDate.addAll(cardListModel.getStudio_list());
                    contentAdapter.notifyDataSetChanged();
                    isLoading = false; // 重置标志位
                    universalBinding.swipeRefreshLayout.setRefreshing(false); // 停止刷新

                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();            //请求失败
                    Log.e("UniversalDisplayFragment", "数据加载错误：" + e.getMessage());
                    isLoading = false; // 重置标志位
                    universalBinding.swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
                    ToastUtil.toastShortMessage("加载失败，请稍后重试");
                }

                @Override
                public void onComplete() {

                }
            }); //
        }).start();


    }


    /**
     * 获取3级菜单
     */
    private void getLevel3() {
        Type type = new TypeToken<LzyResponse<LeftModel>>() {
        }.getType();
        APIService.<LzyResponse<LeftModel>>getData(type, Urls.LIST_LEVEL + "?level=3").subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<LeftModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet"})
            @Override
            public void onNext(LeftModel leftLevel3Model) {
                if (leftLevel3Model.getTag_list().isEmpty()) {
                    return;
                }
                level3Date.clear();
                level3Date.add(new LeftMenuModel(0, "全部", false));
                level3Date.addAll(leftLevel3Model.getTag_list());
                for (LeftMenuModel model : level3Date) {
                    model.setSelect(false);
                }
                level3Date.get(0).setSelect(true);
                screenAdapter.notifyDataSetChanged();
                getCardInfoDate(level3ListDate);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }
}
